package com.zcsy.manage.owner.controller.common;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zcsy.commons.constants.Constants;
import com.zcsy.commons.constants.OwnerConstants;
import com.zcsy.commons.model.RequestConstants;
import com.zcsy.commons.model.RequestJson;
import com.zcsy.commons.unique.UniqueNumberUtils;
import com.zcsy.commons.util.DateUtils;
import com.zcsy.manage.model.base.CellInfo;
import com.zcsy.manage.model.base.ShopInfo;
import com.zcsy.manage.model.mall.GoodsComment;
import com.zcsy.manage.model.property.FeeBillConfig;
import com.zcsy.manage.model.system.User;
import com.zcsy.manage.service.base.ICellInfoService;
import com.zcsy.manage.service.base.IShopInfoService;
import com.zcsy.manage.service.mall.IGoodsCommentService;
import com.zcsy.manage.service.property.IFeeBillService;
import com.zcsy.manage.service.system.IDistrictInfoService;

/**
 * @Title: CommonController.java
 * @Package： com.zcsy.manage.owner.controller.common 
 * @Description: 〈通用管理类〉
 * @author yangfan 373188993@qq.com
 * @Copyright: 2016 武汉恒数利通信息技术有限公司 All rights reserved.
 * @date 2016年6月29日
 * @version 1.0
 * @see JDK1.7.0_75
 * @since
 */

@Controller
@RequestMapping(value= "common")
public class CommonController {
    
    @Autowired
    private IGoodsCommentService goodsCommentService;
    
    @Autowired
    private IFeeBillService feeBillService;
    
    @Autowired
    private ICellInfoService cellInfoService;
    
    @Autowired
    private IDistrictInfoService districtInfoService;
    
    @Autowired
    private IShopInfoService shopInfoService;
    
    private static final int NEW_SHOP = 1;
    
    /**
     * @Description 通用返回wap页面接口
     * @param type 返回url类型 1:停车缴费说明 2:停车缴费发票须知 3:物业缴费说明 4:物业缴费发票须知 5:条款与规则 6:关于我们 7:帮助手册
     * @return result 返回url
     * @author yangfan 373188993@qq.com
     * @date 2016年6月29日
     */
    @RequestMapping(value = "getWaps")
    @ResponseBody
    public RequestJson getWaps(Integer type ,String goodsId, String cellId, String noticeId,Integer pNo,
                               String contactor, String contactorPhone, Integer provinceId, Integer cityId,
                               String descrip, String shopCategoryId) {
        
        RequestJson result = new RequestJson();
        try {
            if (type != null) {
                switch (type) {
                    case OwnerConstants.GET_WAP_TYPE_PARKING_PAY_INFO:
                        result.setResultCode(OwnerConstants.RESULT_CODE_SUCCESS);
                        result.setMsg("返回成功！");
                        result.setObj(OwnerConstants.WAP_URL + "/common/getStopCarInstruction");
                        break;
                        
                    case OwnerConstants.GET_WAP_TYPE_PARKING_INVOICE_INFO:
                        result.setResultCode(OwnerConstants.RESULT_CODE_SUCCESS);
                        result.setMsg("返回成功！");
                        result.setObj(OwnerConstants.WAP_URL + "/common/getStopCarInvoiceNotice");
                        break;
                        
                    case OwnerConstants.GET_WAP_TYPE_PROPERTY_FEE_INFO:
                        result.setResultCode(OwnerConstants.RESULT_CODE_SUCCESS);
                        result.setMsg("返回成功！");
                        result.setObj(OwnerConstants.WAP_URL + "/common/getPropertyInstruction?cellId=" + cellId);
                        break;
                        
                    case OwnerConstants.GET_WAP_TYPE_PROPERTY_INVOICE_INFO:
                        result.setResultCode(OwnerConstants.RESULT_CODE_SUCCESS);
                        result.setMsg("返回成功！");
                        result.setObj(OwnerConstants.WAP_URL + "/common/getPropertyInvoiceNotice");
                        break;
                    case OwnerConstants.GET_WAP_TYPE_TERMS_AND_RULES:
                        result.setResultCode(OwnerConstants.RESULT_CODE_SUCCESS);
                        result.setMsg("返回成功！");
                        result.setObj(OwnerConstants.WAP_URL + "/common/getTermsAndRules");
                        break;
                    case OwnerConstants.GET_WAP_TYPE_ABOUTUS:
                        result.setResultCode(OwnerConstants.RESULT_CODE_SUCCESS);
                        result.setMsg("返回成功！");
                        result.setObj(OwnerConstants.WAP_URL + "/common/getAboutUs");
                        break;
                        
                    case OwnerConstants.GET_WAP_TYPE_HELP:
                        result.setResultCode(OwnerConstants.RESULT_CODE_SUCCESS);
                        result.setMsg("返回成功！");
                        result.setObj(OwnerConstants.WAP_URL + "/common/getHelpManual");
                        break;
                    case OwnerConstants.GET_WAP_GOODS_COMMENT:
                        result.setResultCode(OwnerConstants.RESULT_CODE_SUCCESS);
                        result.setMsg("返回成功！");
                        result.setObj(OwnerConstants.WAP_URL + "/common/getGoodsComment?goodsId="+ goodsId +"&state=1&pNo=" + pNo );
                        break;
                    case OwnerConstants.GET_WAP_REGISTER_PROTOCOL:
                        result.setResultCode(OwnerConstants.RESULT_CODE_SUCCESS);
                        result.setMsg("返回成功！");
                        result.setObj(OwnerConstants.WAP_URL + "/common/getRegisterProtocol");
                        break;
                    case OwnerConstants.GET_WAP_INTEGRAL_INFO:
                        result.setResultCode(OwnerConstants.RESULT_CODE_SUCCESS);
                        result.setMsg("返回成功！");
                        result.setObj(OwnerConstants.WAP_URL + "/common/getIntegralInfo");
                        break;
                    case OwnerConstants.GET_WAP_SIGN_INFO:
                        result.setResultCode(OwnerConstants.RESULT_CODE_SUCCESS);
                        result.setMsg("返回成功！");
                        result.setObj(OwnerConstants.WAP_URL + "/common/getSignInfo");
                        break;
                    case OwnerConstants.GET_OPEN_SHOP:
                        result.setResultCode(OwnerConstants.RESULT_CODE_SUCCESS);
                        result.setMsg("返回成功！");
                        result.setObj(OwnerConstants.WAP_URL + "/common/gotoOpenShop?contactor="+contactor+
                                      "&contactorPhone="+contactorPhone+"&provinceId="+provinceId+"&cityId="+
                                      cityId+"&descrip="+descrip+"&shopCategoryId="+shopCategoryId+"&cellId="+cellId);
                        
//                        //测试用
//                        result.setObj("http://192.168.2.165:8080/ownerConn/common/gotoOpenShop?contactor="+contactor+
//                            "&contactorPhone="+contactorPhone+"&provinceId="+provinceId+"&cityId="+
//                            cityId+"&descrip="+descrip+"&shopCategoryId="+shopCategoryId+"&cellId="+cellId);
                        break;
                    default:
                        result.setResultCode(OwnerConstants.RESULT_EXCEPTION_FALSE);
                        result.setMsg("无此返回类型！");
                        break;
                }
                
            } else {
                result.setResultCode(OwnerConstants.RESULT_EXCEPTION_FALSE);
                result.setMsg("返回失败！");
            }
        } catch (Exception e) {
            result.setSuccess(false);
            result.setResultCode(OwnerConstants.RESULT_EXCEPTION_FALSE);
            result.setMsg("网络异常");
        }
        return result;
    }
    
    /**
     * @Description 返回条款与规则说明wap页面<br>
     * 
     * @param model
     * @return 返回条款与规则说明wap页面
     * @author caiyinli 13277030520@163.com
     * @date 2016年7月14日
     * @see 
     */
    @RequestMapping(value = "getTermsAndRules")
    public String getTermsAndRules(Model model) {
        return "system/TermsAndRules/TermsAndRules";
    }
    
    /**
     * @Description 返回停车缴费说明说明wap页面<br>
     * 
     * @param model
     * @return 返回停车缴费说明说明wap页面
     * @author caiyinli 13277030520@163.com
     * @date 2016年7月14日
     * @see 
     */
    @RequestMapping(value = "getStopCarInstruction")
    public String getStopCarInstruction(Model model) {
        
    	return "system/instruction/stopCarInstruction";
    }
    
    
    /**
     * @Description 返回物业缴费说明wap页面<br>
     * 
     * @param model
     * @return 返回物业缴费说明wap页面
     * @author caiyinli 13277030520@163.com
     * @date 2016年7月14日
     * @see 
     */
    @RequestMapping(value = "getPropertyInstruction")
    public String getPropertyInstruction(Model model ,String cellId) {
        FeeBillConfig feeBillConfig= feeBillService.getFeeBillConfigByCellId(cellId);
        model.addAttribute("feeBillConfig", feeBillConfig);
    	return "system/instruction/propertyInstruction";
    }
    
    /**
     * @Description 返回停车缴费发票须知wap页面<br>
     * 
     * @param model
     * @return 返回停车缴费发票须知wap页面
     * @author caiyinli 13277030520@163.com
     * @date 2016年7月14日
     * @see 
     */
    @RequestMapping(value = "getStopCarInvoiceNotice")
    public String getStopCarInvoiceNotice(Model model) {
    	return "system/instruction/stopCarInvoiceNotice";
    }
    
    /**
     * @Description 返回停车缴费发票须知wap页面<br>
     * 
     * @param model
     * @return 返回停车缴费发票须知wap页面
     * @author caiyinli 13277030520@163.com
     * @date 2016年7月14日
     * @see 
     */
    @RequestMapping(value = "getPropertyInvoiceNotice")
    public String getPropertyInvoiceNotice(Model model) {
    	return "system/instruction/propertyInvoiceNotice";
    }
    
    /**
     * @Description 返回关于我们页面<br>
     * 
     * @param model
     * @return 返回关于我们页面
     * @author caiyinli 13277030520@163.com
     * @date 2016年7月14日
     * @see 
     */
    @RequestMapping(value = "getAboutUs")
    public String getAboutUs(Model model) {
    	return "system/aboutus/aboutUs";
    }
    
    /**
     * @Description 返回帮助手册页面<br>
     * 
     * @param model
     * @return 返回帮助手册页面
     * @author caiyinli 13277030520@163.com
     * @date 2016年7月14日
     * @see 
     */
    @RequestMapping(value = "getHelpManual")
    public String getHelpManual(Model model) {
    	return "system/help/help";
    }
    
    /**
     * @Description 返回注册协议页面<br>
     * 
     * @param model
     * @return 返回注册协议页面
     * @author yangfan 373188993@qq.com
     * @date 2016年8月26日
     * @see 
     */
    @RequestMapping(value = "getRegisterProtocol")
    public String getHelpManual(Model model,String cellId) {
        return "system/registerProtocol/registerProtocol";
    }
    
    /**
     * @Description 返回积分说明页面<br>
     * 
     * @param model
     * @return 返回积分说明页面
     * @author yangfan 373188993@qq.com
     * @date 2016年8月26日
     * @see 
     */
    @RequestMapping(value = "getIntegralInfo")
    public String getIntegralInfo(Model model,String cellId) {
        return "system/instruction/integralInfo";
    }
    
    /**
     * @Description 返回签到说明页面<br>
     * 
     * @param model
     * @return 返回注册协议页面
     * @author yangfan 373188993@qq.com
     * @date 2016年8月26日
     * @see 
     */
    @RequestMapping(value = "getSignInfo")
    public String getSignInfo(Model model,String cellId) {
        return "system/instruction/SignInfo";
    }
    
    /**
     * @Method: goodsComment
     * @Description 商品评论列表接口（返回给wap页面用）
     * @param goodsId 商品id
     * @param pNo 分页
     * @param state 页面改变状态 1：全部 2：好评 3：中评 4：差评<br>
     * @return 
     * @author yangfan 373188993@qq.com
     * @date 2016年8月25日
     * @see 
     */
    @RequestMapping(value = "getGoodsComment")
    public String getGoodsComment(String goodsId,Integer state, Model model ,Integer pNo) {
        
        try {
            GoodsComment commentCount = new GoodsComment();
            GoodsComment goodsComment = new GoodsComment();
            goodsComment.setState(state);
            goodsComment.setGoodsId(goodsId);
            // 指定默认为首页
            if (pNo == null || pNo < OwnerConstants.PAGE_NO) {
                pNo = OwnerConstants.PAGE_NO;
            }
            
            // 此处添加PageHelper将会走拦截器，进行分页，分页方法只针对紧跟着PageHelper的查询方法有效
            PageHelper.startPage(pNo, Constants.PAGE_SIZE);
            
            // 根据商品id查询评论
            List<GoodsComment> goodsCommentList = goodsCommentService.selectCommentBygoodsIdAndState(goodsComment);
            PageInfo<GoodsComment> goodsCommentP = new PageInfo<GoodsComment>(goodsCommentList);
            
            //统计评论 各星级统计数量
            List<GoodsComment> goodsCommentCount = goodsCommentService.getGoodsCommentCount(goodsId);
            
            //设置评论数 ，无此类型评论置0,goodsCommentCount取出的数据按1，2，3，4，5颗星依次统计
            int oneStar   = 0;
            int twoStar   = 0;
            int threeStar = 0;
            int fourStar  = 0;
            int fiveStar  = 0;
            for(GoodsComment comment : goodsCommentCount) {
                switch (comment.getScore()) {
                    case Constants.COMMENT_SCORE_ONE:
                        oneStar = comment.getCount();
                        break;
                    case Constants.COMMENT_SCORE_TWO:
                        twoStar = comment.getCount();
                        break;
                    case Constants.COMMENT_SCORE_THREE:
                        threeStar = comment.getCount();
                        break;
                    case Constants.COMMENT_SCORE_FORE:
                        fourStar = comment.getCount();
                        break;
                    case Constants.COMMENT_SCORE_FIVE:
                        fiveStar = comment.getCount();
                        break;
                    default:
                        break;
                    }
            }
            commentCount.setBadComment(oneStar);
            commentCount.setNormalComment(twoStar + threeStar);
            commentCount.setGoodComment(fourStar + fiveStar);
            
            //计算评论总数
            Integer total = oneStar+twoStar+threeStar+fourStar+fiveStar;
            
            model.addAttribute("commentCount", commentCount);
            model.addAttribute("goodsComment", goodsCommentP);
            model.addAttribute("total", total);
            model.addAttribute("goodsId",goodsId);
            model.addAttribute("state", state);
            
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        return "goods/AllGoodComment";
    }
    
    /**
     * @description 我要开店-小区分类
     * @param parentId 父级（市）id
     * @author chenxin
     * @date 2016年8月11日下午5:30:27
     */
    @RequestMapping(value = "cellList", method = RequestMethod.GET)
    @ResponseBody
    public RequestJson cellList(Model model, String city) {
        RequestJson result = new RequestJson();
        try {
            List<CellInfo> cellInfos = cellInfoService.getCells(city);

            result.setSuccess(true);
            result.setObj(cellInfos);
        } catch (Exception e) {
            result.setSuccess(false);
        }
        return result;
    }
    
    /**
     * @description 跳转到营业执照填写页面
     * @author chenxin
     * @date 2016年8月12日上午11:25:00
     */
    /**
     * @Description: 添加部分为：获取用户信息，以此判断是登陆前开店还是登录后开店，决定营业执照填写页面中的返回按钮的返回页面
     * @param shopId 商铺id
     * @param req 请求
     * @return 跳转到营业执照填写页面
     * @author huangls 1449700087@qq.com
     * @date 2016年8月16日
     */
    @RequestMapping(value = "gotoOpenShop", method = RequestMethod.GET)
    public String gotoOpenShop(Model model, String contactor, String contactorPhone, Integer provinceId, Integer cityId,
            String descrip, String shopCategoryId, String cellId, HttpServletRequest req) {
        
        Integer areaId = null;
        
        //获取当前登陆的用户的信息
        User user = (User)req.getSession().getAttribute(RequestConstants.USER_SESSION_ID);
        
        //根据小区id查找区县id（app中没设计区县）
        CellInfo cellInfo = cellInfoService.selectByPrimaryKey(cellId);
        if(cellInfo != null) {
            areaId = cellInfo.getAreaId();
        }
        
        model.addAttribute("user", user);
        model.addAttribute("provinceList",districtInfoService.getDistrictInfoByLevel((int)Constants.MENU_LEVEL_FIREST));
        model.addAttribute("contactor", contactor);
        model.addAttribute("contactorPhone", contactorPhone);
        model.addAttribute("provinceId", provinceId);
        model.addAttribute("cityId", cityId);
        model.addAttribute("areaId", areaId);
        model.addAttribute("cellId", cellId);
        model.addAttribute("descrip", descrip);
        model.addAttribute("shopCategoryId", shopCategoryId);
        return "openShop";
    }
    
    /**
     * @description 保存营业执照信息
     * @author chenxin
     * @date 2016年8月15日上午9:31:22
     */
    @RequestMapping(value = "saveLisence", method = RequestMethod.POST)
    @ResponseBody
    public RequestJson saveLisence(String contactor, String contactorPhone, Integer provinceId, 
            Integer cityId, Integer areaId, String cellId, String descrip, String shopCategoryId, String shopName, 
            String companyName, String businessLicense, String legalName, String legalIdcard, String legalIdcardPhoto, 
            String businessLicenseProvinceid,String  businessLicenseCityid, String businessLicenseAreaid, 
            String businessLicenseAddress, String registerDate,String beginDate, String endDate, Integer registerMoney,
            String businessScope,String businessLicensePhoto,Integer companyProvinceid,Integer companyCityid,
            Integer companyAreaid, String companyAddress,String companyPhone,String urgentContactor,String urgentContactorPhone) {
        
        RequestJson result =new RequestJson();
        try{
            
        ShopInfo shopInfo = new ShopInfo();
        shopInfo.setId(UniqueNumberUtils.get18UniqueNumber());
        shopInfo.setContactor(contactor);
        shopInfo.setContactorPhone(contactorPhone);
        shopInfo.setProvinceId(provinceId);
        shopInfo.setCityId(cityId);
        shopInfo.setAreaId(areaId);
        shopInfo.setCellId(cellId);
        shopInfo.setDescrip(descrip);
        shopInfo.setShopCategoryId(shopCategoryId);
        shopInfo.setName(shopName);
        shopInfo.setCompanyName(companyName);
        shopInfo.setBusinessLicense(businessLicense);
        shopInfo.setLegalName(legalName);
        shopInfo.setLegalIdcard(legalIdcard);
        shopInfo.setLegalIdcardPhoto(legalIdcardPhoto);
        shopInfo.setBusinessLicenseProvinceid(businessLicenseProvinceid);
        shopInfo.setBusinessLicenseCityid(businessLicenseCityid);
        shopInfo.setBusinessLicenseAreaid(businessLicenseAreaid);
        shopInfo.setBusinessLicenseAddress(businessLicenseAddress);
        shopInfo.setRegisterDate(DateUtils.stringToDate(registerDate));
        shopInfo.setBeginDate(DateUtils.stringToDate(beginDate));
        shopInfo.setEndDate(DateUtils.stringToDate(endDate));
        shopInfo.setRegisterMoney(registerMoney);
        shopInfo.setBusinessScope(businessScope);
        shopInfo.setBusinessLicensePhoto(businessLicensePhoto);
        shopInfo.setCompanyProvinceid(companyProvinceid);
        shopInfo.setCompanyCityid(companyCityid);
        shopInfo.setCompanyAreaid(companyAreaid);
        shopInfo.setCompanyAddress(companyAddress);
        shopInfo.setCompanyPhone(companyPhone);
        shopInfo.setUrgentContactor(urgentContactor);
        shopInfo.setUrgentContactorPhone(urgentContactorPhone);
        shopInfo.setState(NEW_SHOP);
        
        shopInfoService.insert(shopInfo);
        result.setMsg("保存成功！");
        result.setSuccess(true);
        
        } catch(Exception e) {
            result.setMsg("保存异常");
            result.setSuccess(false);
        }
        return result;
    }
}
